package com.wxzhou.wangzhuan.scheduler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxzhou.wangzhuan.constants.LoginEvent;
import io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.redis.datasource.stream.StreamCommands;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 登录日志测试数据，模拟发布到redis进行订阅
 */
@ApplicationScoped
public class RedisLoginPublishService {

    private static final Logger logger = LoggerFactory.getLogger(RedisLoginPublishService.class);
    private static final String STREAM_KEY = "login:events";

    private final StreamCommands<String, String, String> streamCommands;
    private final ObjectMapper objectMapper;

    @Inject
    public RedisLoginPublishService(RedisDataSource redisDataSource, ObjectMapper objectMapper) {
        this.streamCommands = redisDataSource.stream(String.class, String.class, String.class);
        this.objectMapper = objectMapper;
    }

    //    @Scheduled(every = "1s", executionMaxDelay = "100ms")
    public void publishMockLoginEvents() {
        try {
            // 生成模拟登录事件
            LoginEvent loginEvent = generateMockLoginEvent();

            // 将事件序列化为JSON字符串
            String eventJson = objectMapper.writeValueAsString(loginEvent);

            // 创建消息数据
            Map<String, String> messageData = new HashMap<>();
            messageData.put("data", eventJson);

            // 发布到Redis Stream
            String messageId = streamCommands.xadd(STREAM_KEY, messageData);

            logger.info("Published mock login event to Redis stream with ID: {}", messageId);
        } catch (Exception e) {
            logger.error("Error publishing mock login event to Redis stream", e);
        }
    }

    private LoginEvent generateMockLoginEvent() {
        Random random = new Random();

        // 随机生成事件数据
        String deviceId = "device-" + UUID.randomUUID().toString().substring(0, 8);
        Long userId = (long) (10000 + random.nextInt(90000));
        String ipAddress = "192.168.1." + random.nextInt(255);
        Integer loginType = random.nextInt(3);
        Long loginTime = System.currentTimeMillis();
        boolean success = random.nextBoolean();

        // 根据成功与否创建不同的事件
        if (success) {
            return LoginEvent.success(deviceId, userId, ipAddress, loginType, loginTime);
        } else {
            String[] failureReasons = {"密码错误", "账户锁定", "验证码错误", "账户不存在"};
            String failureReason = failureReasons[random.nextInt(failureReasons.length)];
            return LoginEvent.fail(deviceId, ipAddress, loginType, failureReason, loginTime);
        }
    }
}